<template>
	<view>
		<cu-custom bgColor="bg-orange" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">倒计时</block>
		</cu-custom>
		<view class="bigbox">
			<view class="boxx">
				<view class="boxxx">
					<view class="nowtime">
						当地时间:<br>{{nowtime}}
					</view>
				</view>
			</view>
			<view class="box">
				<view class="container" v-for="(item,index) in form" :key="index">
					<uni-swipe-action>
						<uni-swipe-action-item :right-options="options2" :threshold="0"
							@click="bindClick($event,index)">
							<view class="content-box" @click="contentClick(index)">
								<view class="content-text">
									<view class="left">
										<view class="top">
											距离
											<text class="box1">{{item.content}}</text>
										</view>
										<view class="buttom">{{item.time}}</view>
									</view>
									<view class="right" v-if="item.daysDifference>0">
										还有
										<text class="timeleft">
											{{item.daysDifference}}
										</text>
										天
									</view>
									<view class="right" v-else-if="item.daysDifference==0">
										就是今天!
									</view>
									<view class="right" v-else>
										已过去
										<text class="timeleft">
											{{Math.abs(item.daysDifference)}}
										</text>
										天
									</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>
			<view class="add" @click="add">
				<van-icon name="plus" size='50rpx' />
			</view>
			<van-popup :show="showadd" position="bottom" :round="true" custom-style='height:500rpx;' @close="Closeadd">
				<view class="picker">
					<view class="name">
						<van-cell-group>
							<van-field :value="name" placeholder="倒计时名称" @change="onChange" size='large' />
						</van-cell-group>
					</view>
					<view class="time">
						<view class="date" @click="date">
							<van-icon name="clock-o" size='50rpx' />
							<text>日期</text>
						</view>
						<view v-if="istime" class="box1">
							<text>{{Alltime}}</text>
						</view>
					</view>
					<view class="btn">
						<view class="commit" @click="commit">
							<van-icon name="plus" size='50rpx' />
						</view>
					</view>
				</view>
			</van-popup>
			<van-popup :show="showupdate" position="bottom" :round="true" custom-style='height:500rpx;'
				@close="Closeupdate">
				<view class="picker">
					<view class="name">
						<van-cell-group>
							<van-field :value="name" placeholder="倒计时名称" @change="onChange" size='large' />
						</van-cell-group>
					</view>
					<view class="time">
						<view class="date" @click="date">
							<van-icon name="clock-o" size='50rpx' />
							<text>日期</text>
						</view>
						<view class="box1">
							<text>{{goaltimes}}</text>
						</view>
					</view>
					<view class="btn">
						<view class="commit" @click="update(index)">
							<van-icon name="success" size='50rpx' />
						</view>
					</view>
				</view>
			</van-popup>
			<van-popup :show="showpicker" position="bottom" :round="true" custom-style='height:500rpx;'>
				<van-datetime-picker type="date" :value="currentDate" :show='showpicker' @confirm='confirm'
					@cancel='cancel' @input="onInput" />
			</van-popup>
		</view>
	</view>

</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				showadd: false,
				showpicker: false,
				show: false,
				showupdate: false,
				isOpened: 'none',
				minDate: new Date().getTime(),
				currentDate: new Date().getTime(),
				year: new Date().getFullYear(),
				month: new Date().getMonth() + 1,
				day: new Date().getDate(),
				nowyear: new Date().getFullYear(),
				nowmonth: new Date().getMonth() + 1,
				nowday: new Date().getDate(),
				istime: false,
				updatename: '',
				updatetime: '',
				name: '',
				index: 0,
				second: 2,
				form: [],
				options2: [{
						text: '编辑',
						style: {
							backgroundColor: '#a5dff9',
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#f15c5c',


						}
					}
				],
			};
		},
		onLoad() {
			if (!this.countdown.length) this.getcoundtdown()
			else {
				this.form = JSON.parse(JSON.stringify(this.countdown));
				this.form.forEach((item) => {
					item.daysDifference = this.calculatetime(item.time)
				})
			}
		},
		computed: {
			...mapState('m_count', ['countdown']),
			goaltimes() {
				return this.year + '/' + this.month + '/' + this.day;
			},
			Alltime() {
				return this.year + '年' + this.month + '月' + this.day + '日';
			},
			nowtime() {
				return this.nowyear + '年' + this.nowmonth + '月' + this.nowday + '日';
			}
		},
		methods: {
			...mapMutations('m_count', ['updatecountdown']),
			async getcoundtdown() {
				try {
					const data = await uni.$http.get('/get/getcountdown')
					this.updatecountdown(data.data.data)
					this.form = JSON.parse(JSON.stringify(this.countdown));
					this.form.forEach((item) => {
						item.daysDifference = this.calculatetime(item.time)
					})

				} catch (e) {
					//TODO handle the exception
				}

			},

			calculatetime(time) {
				// 获取当前时间
				let currentDate = new Date();

				// 指定目标日期
				let targetDate = new Date(time);

				// 计算时间差（以毫秒为单位）
				let timeDifference = targetDate.getTime() - currentDate.getTime();

				// 将时间差转换为天数
				let daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
				return daysDifference;
			},
			onChange(e) {
				this.name = e.detail
			},
			Closeadd() {
				this.showadd = false
				this.name = ''
				this.currentDate = new Date().getTime()
				this.istime = false
			},
			Closeupdate() {
				this.showupdate = false
				this.name = ''
				this.currentDate = new Date().getTime()
			},
			onInput(e) {
				let date = new Date(e.detail);
				this.year = date.getFullYear();
				this.month = date.getMonth() + 1; // 月份从0开始，所以需要加1
				this.day = date.getDate();
			},
			contentClick(index) {
				this.index = index
				this.name = this.form[index].content
				this.year = this.form[index].time.split('/')[0]
				this.month = this.form[index].time.split('/')[1]
				this.day = this.form[index].time.split('/')[2]
				this.showupdate = true
			},
			async bindClick(e, index) {
				if (!e.index) {
					this.index = index
					this.name = this.form[index].content
					this.year = this.form[index].time.split('/')[0]
					this.month = this.form[index].time.split('/')[1]
					this.day = this.form[index].time.split('/')[2]
					this.showupdate = true
				} else {
					const array = [...this.countdown]
					array.splice(index, 1)
					const result = await uni.$http.post('/update/updatecountdown', {
						countdown: array
					})
					if (result.data.status === 0) {
						this.updatecountdown(array)
						this.getcoundtdown()
						const timer = setInterval(() => {
							this.second--;
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 2000
							});
							if (this.second <= 0) {
								clearInterval(timer)
								this.showadd = false
								this.istime = false
								this.name = ''
								return
							}
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								duration: 2000
							});
						}, 1000)

					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'error',
							duration: 2000
						});
						this.showadd = false
						this.istime = false
						this.name = ''
					}
				}
			},

			add() {
				this.showadd = true
			},
			confirm() {
				this.showpicker = false
				this.istime = true
			},
			cancel() {
				this.showpicker = false
			},
			date() {
				this.showpicker = true
			},
			async update() {
				if (!this.name) {
					uni.showToast({
						title: '名称不能为空',
						icon: 'none'
					})
					return
				}
				const data = {
					content: this.name,
					time: this.goaltimes
				}
				const array = [...this.countdown]
				array[this.index] = data
				const result = await uni.$http.post('/update/updatecountdown', {
					countdown: array
				})
				if (result.data.status === 0) {
					this.updatecountdown(array)
					this.getcoundtdown()
					const timer = setInterval(() => {
						this.second--;
						uni.showToast({
							title: '更新成功',
							icon: 'success',
							duration: 2000
						});
						if (this.second <= 0) {
							clearInterval(timer)
							this.showupdate = false
							this.istime = false
							this.name = ''
							return
						}
						uni.showToast({
							title: '更新成功！',
							icon: 'success',
							duration: 1000
						});
					}, 1000)
				} else {
					uni.showToast({
						title: '更新失败',
						icon: 'error',
						duration: 2000
					});
					this.showupdate = false
					this.istime = false
					this.name = ''
				}
			},
			async commit() {
				if (!this.name || !this.istime) {
					uni.showToast({
						title: '名称或日期不能为空',
						icon: 'none'
					})
					return
				}
				const data = {
					content: this.name,
					time: this.goaltimes
				}
				const array = [...this.countdown]
				array.push(data)
				const result = await uni.$http.post('/update/updatecountdown', {
					countdown: array
				})
				if (result.data.status === 0) {
					this.updatecountdown(array)
					this.getcoundtdown()

					const timer = setInterval(() => {
						this.second--;
						uni.showToast({
							title: '添加成功',
							icon: 'success',
							duration: 2000
						});
						if (this.second <= 0) {
							clearInterval(timer)
							this.showadd = false
							this.istime = false
							this.name = ''
							return
						}
						uni.showToast({
							title: '添加成功',
							icon: 'success',
							duration: 2000
						});
					}, 1000)

				} else {
					uni.showToast({
						title: '添加失败',
						icon: 'error',
						duration: 2000
					});
					this.showadd = false
					this.istime = false
					this.name = ''
				}
			}
		}
	};
</script>

<style lang="less">
	.boxx {
		width: 100%;
		height: 140rpx;
		position: fixed;
		left: 0;
		z-index: 1;
		background-color: #fff;

		.boxxx {
			width: 270rpx;
			height: 120rpx;
			position: relative;
			background-color: #f9cdad;
			border-radius: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 55%;
			margin-top: 20rpx;
		}
	}

	.box {
		padding-top: 160rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.content-box {
		display: flex;
		flex: 1;
		height: 150rpx;
		padding: 0 15rpx;
		border-radius: 30rpx;
		// background-color: #f9cdad;
		border-bottom-color: #f5f5f5;
		border-bottom-width: 1rpx;
		border-bottom-style: solid;
	}

	.content-text {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left {
			.top {
				font-size: 40rpx;

				text {
					margin-left: 10rpx;
				}
			}

			.buttom {
				font-size: 30rpx;
				color: #D9D4CF;

			}
		}

		.right {
			font-size: 40rpx;

			.timeleft {
				color: #f9cdad;
				font-size: 43rpx;
			}
		}
	}

	.add {
		background-color: #f9cdad;
		height: 100rpx;
		width: 100rpx;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		position: fixed;
		top: 80vh;
		right: 90rpx;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
	}


	.title {
		text-align: center;
		margin-top: 30rpx;
		font-size: 40rpx;

		.success {
			flex: ;
		}

		.smalltitle {
			flex: 5;
		}

		.cancel {
			flex: 2;
		}

	}

	.picker {

		margin-top: 30rpx;
		margin-left: 50rpx;
		font-family: "微软雅黑", Arial, sans-serif;

		.time {
			display: flex;
			margin-top: 20rpx;
			margin-left: 20rpx;

			.date {
				display: flex;
				font-size: 38rpx;

				text {
					margin-left: 20rpx;
				}
			}

			.box1 {
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #f9cdad;
				border-radius: 20rpx;
				margin-left: 20rpx;


				text {
					padding: 10rpx;
				}
			}
		}

		.btn {
			display: flex;
			justify-content: center;
			margin-top: 50rpx;

			.commit {
				background-color: #f9cdad;
				height: 100rpx;
				width: 100rpx;
				border-radius: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
			}
		}

	}
</style>